| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
- import { UserService } from '@/server/modules/users/user.service';
- import { z } from '@hono/zod-openapi';
- import { authMiddleware } from '@/server/middleware/auth.middleware';
- import { ErrorSchema } from '@/server/utils/errorHandler';
- import { AppDataSource } from '@/server/data-source';
- import { AuthContext } from '@/server/types/context';
- import { UserResponseSchema } from '@/server/modules/users/user.schema';
- import { parseWithAwait } from '@/server/utils/parseWithAwait';
- const userService = new UserService(AppDataSource);
- const GetParams = z.object({
- id: z.coerce.number().openapi({
- param: { name: 'id', in: 'path' },
- example: 1,
- description: '用户ID'
- })
- });
- const routeDef = createRoute({
- method: 'get',
- path: '/{id}',
- middleware: [authMiddleware],
- request: {
- params: GetParams
- },
- responses: {
- 200: {
- description: '成功获取用户详情',
- content: { 'application/json': { schema: UserResponseSchema } }
- },
- 404: {
- description: '用户不存在',
- content: { 'application/json': { schema: ErrorSchema } }
- },
- 500: {
- description: '服务器错误',
- content: { 'application/json': { schema: ErrorSchema } }
- }
- }
- });
- const app = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
- try {
- const { id } = c.req.valid('param');
- const user = await userService.getUserById(id);
- if (!user) {
- return c.json({ code: 404, message: '用户不存在' }, 404);
- }
- return c.json(await parseWithAwait(UserResponseSchema, user), 200);
- } catch (error) {
- return c.json({
- code: 500,
- message: error instanceof Error ? error.message : '获取用户详情失败'
- }, 500);
- }
- });
- export default app;
|